<?php
header("Content-type: text/html; charset=utf-8");

if ($_POST) {
    $real_name = trim($_GPC['real_name']);
    $mobile = trim($_GPC['mobile']);
    $authcode = trim($_GPC['authcode']);
    $email = trim($_GPC['email']);

    /*
     * 手机判断
     */
    $member = pdo_fetch("SELECT * FROM " . tablename('bontrip_member')
        . " WHERE mobile = {$mobile} AND uniacid={$uniacid} AND deleted_at is null");
    if (!empty($member)) {
        message('账号已存在！', $this->createMobileUrl('register'), 'error');
    }

    /*
     * 手机验证码判断
     */
    $sms_last = pdo_fetch("SELECT * FROM " . tablename('bontrip_auth_code')
        . " WHERE mobile = '{$mobile}' ORDER BY created_at DESC");
    if (empty($sms_last)) {
        message('验证失败！', $this->createMobileUrl('register'), 'error');
    }

    if ($sms_last['auth_code'] != $authcode) {
        message('验证码错误！', $this->createMobileUrl('register'), 'error');
    }
    if (TIMESTAMP - $sms_last['created_at'] > 300) {
        message('验证码已被使用或超时，请重新获取验证码！', $this->createMobileUrl('register'), 'error');
    }

    // 清理同一openid的的账户
    pdo_update('bontrip_member', array('openid' => ''), array('openid' => $userinfo['openid']));
    //替换字符串，將132替換成0
    $userinfo['avatar'] = str_replace('132', '0', $userinfo['avatar']);
    /*
     * 入库
     */
    $time = TIMESTAMP;
    $member = array(
        'uniacid' => $uniacid,
        'openid' => $userinfo['openid'],
        'avatar' => $userinfo['avatar'],
        'nick_name' => $userinfo['nickname'],
        'real_name' => $real_name,
        'mobile' => $mobile,
        'email' => $email,
        'created_at' => $time,
        'updated_at' => $time,
    );
    pdo_insert('bontrip_member', $member);
    $id = pdo_insertid();

    $member['id'] = $id;
    $_SESSION['vj_member'] = base64_encode(iserializer($member));
    $url = $this->createMobileUrl('me');
    if (!empty($_SESSION['jump_url'])) {
        $url = $_SESSION['jump_url'];
        $_SESSION['jump_url'] = null;
    }
    message('注册成功！', $url, 'success');
}


$title = '注册';
include $this->template('register');